import { Window_Selectable } from "@/windows/Window_Selectable.js";

export class Window_BattleItem extends Window_Selectable {
    constructor(width,height) {
        super(width,height);
    }

    init(width, height) {
        this._list=[];
        this.numberWidth=0;
        this.okHandler=null;
        this.cancelHandler=null;
        this.changedHandler=null;
        super.init(width, height);
    }

    destroy(opts){
        super.destroy(opts);
        this._list.length=0;
        this.okHandler=null;
        this.cancelHandler=null;
        this.cancelHandler=null;
    }

    column(){return 2;}
    viewColumn(){return 2;}
    row(){return Math.ceil(this.length()/this.column());}
    viewRow(){return Math.floor(this.contentsHeight()/this.itemHeight());}
    length(){return this._list.length;}
    itemEnabled(index){return super.itemEnabled(index)&&$gameParty.canUse(this._list[index]);}

    drawItem(index,x,y,width,height){
        let item = this._list[index];
        if (item) {
            let nwidth=this.numberWidth();
            let enabled=this.itemEnabled(index);
            if(!enabled){
                this.changePaintOpacity(false);
            }
            this.drawItemName(item, x , y,width-nwidth);
            this.drawText($gameParty.numItems(item),x+width-nwidth, y, nwidth,height);
            if(!enabled){
                this.changePaintOpacity(true);
            }
        }
    }

    numberWidth() {
        if(!this.numWidth){
            this.numWidth=this.textWidth('000');
        }
        return this.numWidth;
    }

    makeItemList(){
        this._list=$gameParty.items();
    }

    refresh(){
        this.makeItemList();
        super.refresh();
    }

    setHandler(name,callback){
        if(name=='ok'){
            this.okHandler=callback;
        }else if(name=='cancel'){
            this.cancelHandler=callback;
        }else if(name=='changed'){
            this.changedHandler=callback;
        }
    }

    onResponse(index){this.okHandler?.(this._list[index],index);}
    onCancel(){this.cancelHandler?.();}
    onSelectChanged(index,oldIndex){
        this.changedHandler?.(this._list[index],index,this._list[oldIndex],oldIndex);
    }

}